//新增电影渲染导演、类型

$.ajax({
  url: "/director/",
  success: function (data) {
    // console.log(data);
    render(data);
    function render(list) {
      let htmlStr = "";
      list.forEach((d) => {
        htmlStr += `<option value="${d._id}">${d.name}</option>`;
      });
      $("#addMovieDir").html(htmlStr);
    }
  },
});
$.ajax({
  url: "/type/",
  success: function (data) {
    // console.log(data);
    render(data);
    function render(list) {
      let htmlStr = "";
      list.forEach((t) => {
        htmlStr += `<option value="${t._id}">${t.type}</option>`;
      });
      $("#addMovieType").html(htmlStr);
    }
  },
});
//新增电影
//上传图片预览
$("body").on("change", "#imageUpload", function (e) {
  let files = e.target.files;
  //   console.log(files[0]);
  // 2 新建formData对象，将文件加入其中,方便multer插件处理
  let fd = new FormData();
  fd.append("file", files[0]);
  $.ajax({
    url: "/upload/uploadImage",
    success: function (data) {
      console.log(data);
      //预览
      $(".image-frame>img").attr("src", data.data);
    },
    type: "post",
    data: fd,
    //防止jQuery处理了表单数据，因为处理后，后端的multer插件无法自动识别并处理
    contentType: false,
    processData: false,
    cache: false,
  });
});
$("body").on("click", "#addMoviesBtn", function () {
  $.ajax({
    url: "/movie/",
    success: function (data) {
      console.log(data);
      movieRender(data);
      alert("添加成功");
    },
    type: "post",
    data: {
      title: $("#addMoviesName").val(),
      actor: $("#addMoviesActors").val(),
      time: $("#addMoviesTime").val(),
      score: $("#addMoviesScore").val(),
      directorId: $("#addMovieDir").val(),
      typeId: $("#addMovieType").val(),
      imgSrc: $(".image-frame>img").attr("src"),
    },
  });
});
//所有电影数据渲染
function movieRender(list) {
  let htmlStr = "";
  list.forEach((m) => {
    htmlStr += `
        <tr>
                                            <td>${m._id}</td>
                                            <td>${m.title}</td>
                                            <td> ${m.actor}</td>
                                            <td>${m.time}</td>
                                            <td>${m.directorId.name}</td>
                                            <td><img width="100" src="${m.imgSrc}"></td>
                                            <td>${m.typeId.type}</td>
                                            <td>
                                                <a href="#MoviesUpdate" data-id=${m._id} class="modify">修改</a>
                                                <a href="" data-id=${m._id} class="deleteMovie">删除</a>
                                            </td>                                    
    </tr>
        `;
  });
  $("#MoviesTb").html(htmlStr);
}
$.ajax({
  url: "/movie/",
  success: function (data) {
    console.log("所有电影", data);
    movieRender(data);
  },
});
//电影修改跳转，绑定id,渲染导演，类型
$("body").on("click", ".modify", function () {
  let _id = $(this).attr("data-id");
  $("#modifyMovieBtn").attr("data-id", _id);
  $.ajax({
    url: "/director",
    success: function (data) {
      // console.log(data);
      render(data);
      function render(list) {
        let htmlStr = "";
        list.forEach((d) => {
          htmlStr += `<option value="${d._id}">${d.name}</option>`;
        });
        $("#modifyDirector").html(htmlStr);
      }
    },
  });
  $.ajax({
    url: "/type",
    success: function (data) {
      // console.log(data);
      render(data);
      function render(list) {
        let htmlStr = "";
        list.forEach((t) => {
          htmlStr += `<option value="${t._id}">${t.type}</option>`;
        });
        $("#modifyType").html(htmlStr);
      }
    },
  });
});
//修改电影
$("body").on("change", "#modify-image", function (e) {
  let files = e.target.files;
  //   console.log(files[0]);
  // 2 新建formData对象，将文件加入其中,方便multer插件处理
  let fd = new FormData();
  fd.append("file", files[0]);
  $.ajax({
    url: "/upload/uploadImage",
    success: function (data) {
      console.log(data);
      //预览
      $(".image-frame>img").attr("src", data.data);
    },
    type: "post",
    data: fd,
    //防止jQuery处理了表单数据，因为处理后，后端的multer插件无法自动识别并处理
    contentType: false,
    processData: false,
    cache: false,
  });
});
$("body").on("click", "#modifyMovieBtn", function () {
  $.ajax({
    url: "/movie/modifyMovie",
    success: function (data) {
      movieRender(data);
      alert("修改成功");
    },

    type: "post",
    data: {
      content: JSON.stringify({
        _id: $("#modifyMovieBtn").attr("data-id"),
        movie: {
          title: $("#modifyMoviesName").val(),
          actor: $("#modifyMoviesActors").val(),
          time: $("#modifyMoviesTime").val(),
          score: $("#modifyMoviesScore").val(),
          directorId: $("#modifyDirector").val(),
          typeId: $("#modifyType").val(),
          imgSrc: $(".image-frame>img").attr("src"),
        },
      }),
    },
  });
});
//删除电影
$("body").on("click", ".deleteMovie", function (e) {
  e.preventDefault();
  $.ajax({
    url: `/movie/${$(this).attr("data-id")}`,
    success: function (data) {
      console.log(data);
      movieRender(data);
    },

    type: "delete",
  });
});

//增加导演
$("body").on("click", "#addDirectorBtn", function () {
  $.ajax({
    url: "/movie/addDirector",
    type: "post",
    data: { name: $("#addDirectorName").val() },
    success: function (data) {
      console.log(data);
      DirectorRender(data);
    },
  });
});
//渲染导演
function DirectorRender(list) {
  let htmlStr = "";
  list.forEach((d) => {
    htmlStr += `<tr>
    <td>${d._id}</td>
    <td>${d.name}</td>
    <td>
        <a href="#" data-id="${d._id}" class="deleteDirector">删除</a>
    </td>
</tr>`;
  });
  $("#directorList").html(htmlStr);
}
$.ajax({
  url: "/director",
  success: function (data) {
    // console.log(data);
    DirectorRender(data);
  },
});
//删除导演
$("body").on("click", ".deleteDirector", function (e) {
  e.preventDefault();
  let _id = $(this).attr("data-id");
  $.ajax({
    url: `/director/${_id}`,
    success: function (data) {
      console.log(data);
      DirectorRender(data);
    },

    type: "delete",
  });
});

//增加类型
$("body").on("click", "#addTypeBtn", function () {
  $.ajax({
    url: "/type",
    type: "post",
    data: { type: $("#addType").val() },
    success: function (data) {
      console.log(data);
      TypeRender(data);
    },
  });
});
//渲染类型
function TypeRender(list) {
  let htmlStr = "";
  list.forEach((t) => {
    htmlStr += `<tr>
    <td>${t._id}</td>
    <td>${t.type}</td>
    <td>
        <a href="#" data-id="${t._id}" class="deleteType">删除</a>
    </td>
</tr>`;
  });
  $("#typeList").html(htmlStr);
}
$.ajax({
  url: "/type",
  success: function (data) {
    // console.log(data);
    TypeRender(data);
  },
});
//删除类型
$("body").on("click", ".deleteType", function (e) {
  e.preventDefault();
  $.ajax({
    url: `/type/${$(this).attr("data-id")}`,
    success: function (data) {
      console.log(data);
      TypeRender(data);
    },

    type: "delete",
  });
});

//新增演员
$("body").on("click", "#addHeadActorsBtn", function () {
  $.ajax({
    url: "/actor",
    type: `post`,
    data: {
      name: $("#addHeadActorsName").val(),
    },
    success: function (data) {
      console.log(data);
      actorRender(data);
    },
  });
});
//渲染演员列表
function actorRender(list) {
  let htmlStr = "";
  list.forEach((a) => {
    let movieStr = "";
    a.acMovies.forEach((m) => {
      movieStr += m.title + " ";
    });
    htmlStr += `
    <tr>
                                            <td>${a._id}</td>
                                            <td>${a.name}</td>
                                            <td>${movieStr}</td>
                                            <td>
                                                <a href="" data-id="${a._id}" class="deleteActor">删除</a>
                                                <a href="#headActorsAddMovie" data-id="${a._id}" class="link">关联电影</a>
                                            </td>
                                        </tr>
    `;
  });
  $("#headActorsList #classesTb").html(htmlStr);
}
$.ajax({
  url: "/actor",
  success: function (data) {
    console.log("所有演员", data);
    actorRender(data);
  },
});
//删除演员
$("body").on("click", ".deleteActor", function (e) {
  e.preventDefault();
  $.ajax({
    url: `/actor/${$(this).attr("data-id")}`,
    success: function (data) {
      console.log(data);
      actorRender(data);
    },

    type: "delete",
  });
});
//演员关联电影页面渲染电影
$.ajax({
  url: "/movie/",
  success: function (data) {
    render(data);
    function render(list) {
      let htmlStr = "<label>电影列表：</label> <br>";
      list.forEach((m) => {
        htmlStr += `<label ><input type="checkbox" class="movie-check" data-id="${m._id}">${m.title}</label><br>`;
      });
      $(`#movies`).html(htmlStr);
    }
  },
});
//关联跳转传id
$("body").on("click", ".link", function (e) {
  let _id = $(this).attr("data-id");
  $("#linkConfirm").attr("data-id", _id);
});
//关联
$("body").on("click", "#linkConfirm", function (e) {
  let acMovies = [];
  // console.log( $(".movie-check:checked"));
  $selects = $(".movie-check:checked");
  for (let i = 0; i < $selects.length; i++) {
    acMovies.push($($selects[i]).attr("data-id"));
  }
  acMovies = acMovies.join(",");
  $.ajax({
    url: "/actor",
    type: "put",
    data: {
      _id: $("#linkConfirm").attr("data-id"),
      acMovies,
    },
    success: function (data) {
      console.log("关联成功", data);
      actorRender(data)
    },
  });
});
